/*
  	Arkodroid - An Arduino Controller for Android
	Copyright (c) 2013 Miguel Monteiro, Eduardo Peixoto, Rui Pedro Carvalhal, André Braga.
	All rights reserved.
	http://code.google.com/p/arkodroid/
	
	Amarino API by Bonifaz Kaufmann - http://www.amarino-toolkit.net/
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package net.miguelmonteiro.android.arkodroid;

import net.miguelmonteiro.android.arkodroid.Checker.Resource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import at.abraxas.amarino.Amarino;

public class ArkodroidJoystick extends Activity {    
	// Variables
	int threshold = 3;
	final int DELAY = 150;
	long lastchanged;
	String[] values = { "0", "0" };
	
	public static final String TAG = "ArkodroidJoystick";
	
	// Declare objects
	TextView xCoor;
	TextView yCoor;
    
    Button buzzerButton;

    JoystickView joystickL;
    JoystickView joystickR;
	
    /** Check if Bluetooth is ON **/
	@Override 
    protected void onResume() {
		super.onResume();
    	new Checker(this).pass(new Checker.Pass() {
    		@Override public void pass() {
    	    	// Nothing
    	 	}
    	}).check(Resource.BLUETOOTH);
    }

    /** Called when the activity is first created. **/
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main_joystick);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        lastchanged = System.currentTimeMillis();
        
        // Create objects
        xCoor = (TextView)findViewById(R.id.xcoor);
		yCoor = (TextView)findViewById(R.id.ycoor);
		buzzerButton = (Button) findViewById(R.id.buttonBuzzer);

        joystickL = (JoystickView)findViewById(R.id.joystickViewL);
        joystickR = (JoystickView)findViewById(R.id.joystickViewR);

        joystickL.setOnJostickMovedListener(_listenerL);
        joystickR.setOnJostickMovedListener(_listenerR);

		
		buzzerButton.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	Log.i(TAG, "Buzzer command sent");
	        	Amarino.sendDataToArduino(ArkodroidJoystick.this, BluetoothConnect.DEVICE_ADDRESS, 'b', (1));
	        }
	    });
        
        /** CODIGO **/
    }
	
	@Override
	protected void onStop() {
		super.onStop();
	
		Amarino.disconnect(this, BluetoothConnect.DEVICE_ADDRESS);
	}
	
	public void onToggleClicked(View v) {
        // Perform action on clicks
        if (((ToggleButton) v).isChecked()) {
            Toast.makeText(this, R.string.main_light_on, Toast.LENGTH_SHORT).show();
            Amarino.sendDataToArduino(this, BluetoothConnect.DEVICE_ADDRESS, 'l', 1);
        } else {
            Toast.makeText(this, R.string.main_light_auto, Toast.LENGTH_SHORT).show();
            Amarino.sendDataToArduino(this, BluetoothConnect.DEVICE_ADDRESS, 'l', 0);            
        }
    }
	
	private JoystickMovedListener _listenerL = new JoystickMovedListener() {
		@Override
        public void OnMoved(int pan, int tilt) {
			yCoor.setText(Integer.toString(tilt));
			values[0] = Integer.toString(tilt);
			sendValues();
		}

        @Override
        public void OnReleased() {
        	yCoor.setText("released");
			values[0] = Integer.toString(0);
			sendStopValues();
        }
       
        public void OnReturnedToCenter() {
        	yCoor.setText("stopped");
        };
	}; 
	
	private JoystickMovedListener _listenerR = new JoystickMovedListener() {
		@Override
        public void OnMoved(int pan, int tilt) {
			xCoor.setText(Integer.toString(pan));
			values[1] = Integer.toString(pan);
			sendValues();
		}

        @Override
        public void OnReleased() {
        	xCoor.setText("released");
			values[1] = Integer.toString(0);
			sendStopValues();
        }
       
        public void OnReturnedToCenter() {
        	xCoor.setText("stopped");
        };
	}; 
	
	private void sendValues(){
		if (System.currentTimeMillis() - lastchanged > Arkodroid.delay){
			Amarino.sendDataToArduino(ArkodroidJoystick.this, BluetoothConnect.DEVICE_ADDRESS, 'B', values.clone());
			lastchanged = System.currentTimeMillis();
		}
	}
	
	private void sendStopValues(){
		Amarino.sendDataToArduino(ArkodroidJoystick.this, BluetoothConnect.DEVICE_ADDRESS, 'B', values.clone());
	}
	
	/** Hard "Back button" pressed **/
	@Override
    public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder
    	.setTitle(R.string.exit)
    	.setMessage(R.string.wantexit)
    	.setIcon(android.R.drawable.ic_dialog_alert)
    	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int which) {			      	
    	    	finish();
    	    }
    	})
    	.setNegativeButton(R.string.no, null)
    	.show();
    } 
    
	/** Menu creation **/
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.menu, menu);        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case R.id.connecttext:
            	startActivity(new Intent(this, BluetoothConnect.class));                
        		break;
            case R.id.settingstext: 
            	startActivity(new Intent(this, net.miguelmonteiro.android.arkodroid.Settings.class));
                return true;
            case R.id.abouttext:
                new AlertDialog.Builder(ArkodroidJoystick.this)
                        .setTitle(getString(R.string.app_name) + " " + getVersion())
                        .setView(View.inflate(this, R.layout.about, null))
                        .setIcon(R.drawable.ic_launcher_small)
                        .setPositiveButton(R.string.about_email, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                        		Intent i = new Intent(Intent.ACTION_SEND);
                        		i.setType("message/rfc822");
                        		i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"mail@miguelmonteiro.net"});
                        		i.putExtra(Intent.EXTRA_SUBJECT, "Aplicação Arkodroid");
                        		i.putExtra(Intent.EXTRA_TEXT   , "");
                        		try {
                        		    startActivity(Intent.createChooser(i, "Enviar email..."));
                        		} catch (android.content.ActivityNotFoundException ex) {
                        		    Toast.makeText(ArkodroidJoystick.this, R.string.about_noemailinstalled, Toast.LENGTH_SHORT).show();
                        		}
                            }
                        }).setNeutralButton(R.string.about_website, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            	Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/p/arkodroid/"));
                    			startActivity(browserIntent);
                            }
                        }).setNegativeButton(R.string.back, null)
                        .show();                
                break;
        }
        return true;
    }
    
    /** Return the Version of the App **/
    private String getVersion() {
            String version = "1.0";
            try {
                    PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
                version = pi.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                Log.e(TAG, "Package name not found", e);
            }
            return version;
    }
}
